package cn.schoolwow.quickdao.module.initial.flow.table;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.entity.*;
import cn.schoolwow.quickdao.module.database.ddl.action.flow.column.AlterTableColumnFlow;
import cn.schoolwow.quickdao.module.database.ddl.query.flow.entity.GetEntityListFlow;
import cn.schoolwow.quickdao.module.database.ddl.query.flow.property.GetEntityPropertyListFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AutomaticUpdatePropertyFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);

        if(!quickDAOConfig.databaseOption.automaticUpdateProperty){
            flowContext.remark("跳过自动更新属性");
            return;
        }
        Map<String, Entity> entityMap = quickDAOConfig.databaseContext.entityMap;
        if (null == entityMap || entityMap.isEmpty()) {
            flowContext.remark("未扫描到任何实体类!请设置包路径或者实体类!");
            return;
        }

        List<Entity> databaseEntityList = (List<Entity>) flowContext.getQuickFlow().executeFlow(
                new GetEntityListFlow(),
                new GetEntityPropertyListFlow()
        ).checkData("entityList");

        //待修改的字段
        Map<String,List<PropertyOption>> alterPropertyMap = new HashMap<>();
        for(Entity entity:entityMap.values()){
            for(Entity databaseEntity:databaseEntityList){
                if(entity.clazz.getSimpleName().equalsIgnoreCase(DatabaseUpgrade.class.getSimpleName())
                        ||entity.clazz.getSimpleName().equalsIgnoreCase(SqlLog.class.getSimpleName())
                ){
                    continue;
                }
                if(null!=quickDAOConfig.databaseOption.updateTableNameList&&!quickDAOConfig.databaseOption.updateTableNameList.isEmpty()){
                    if(!quickDAOConfig.databaseOption.updateTableNameList.contains(entity.tableName)){
                        continue;
                    }
                }
                if(!entity.tableName.equalsIgnoreCase(databaseEntity.tableName)){
                    continue;
                }
                for(Property property:entity.properties){
                    for(Property databaseProperty:databaseEntity.properties){
                        if(!property.column.equalsIgnoreCase(databaseProperty.column)){
                            continue;
                        }
                        if(shouldUpdate(property, databaseProperty)){
                            PropertyOption propertyOption = new PropertyOption();
                            propertyOption.id = property.id;
                            propertyOption.strategy = property.strategy;
                            propertyOption.notNull = property.notNull;
                            propertyOption.column = property.column;
                            propertyOption.comment = property.comment;
                            propertyOption.columnType = property.columnType;
                            propertyOption.range = property.range;
                            if(!alterPropertyMap.containsKey(entity.tableName)){
                                alterPropertyMap.put(entity.tableName, new ArrayList<>());
                            }
                            alterPropertyMap.get(entity.tableName).add(propertyOption);
                        }
                    }
                }
            }
        }

        //修改字段
        for(Map.Entry<String,List<PropertyOption>> entry:alterPropertyMap.entrySet()){
            for(PropertyOption propertyOption:entry.getValue()){
                flowContext.getQuickFlow().startFlow(new AlterTableColumnFlow())
                        .putTemporaryData("tableName", entry.getKey())
                        .putTemporaryData("propertyOption", propertyOption)
                        .execute();
            }
        }
    }

    @Override
    public String name() {
        return "自动更新字段";
    }

    private boolean shouldUpdate(Property property, Property databaseProperty){
        if(property.id||null!=property.strategy){
            return false;
        }
        if(property.createdAt||property.updateAt){
            return false;
        }
        //判断注释是否相同
        if(null!=property.comment&&!property.comment.isEmpty()&&!property.comment.equalsIgnoreCase(databaseProperty.comment)){
            return true;
        }
        //判断notnull属性
        if(null!=property.notNull&&!property.notNull.equals(databaseProperty.notNull)){
            return true;
        }
        return false;
    }

}
